<?php

namespace Admin\Models\school;

use Admin\Models\BaseModel;
use Helpers\Main;
use Phalcon\Di;
class XhschoolClassstudent extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iSCSId;

    /**
     *
     * @var integer
     */
    public $iSCLId;

    /**
     *
     * @var string
     */
    public $iStudId;

    /**
     *
     * @var integer
     */
    public $iOp;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var string
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;

    /**
     *
     * @var string
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        $this->setSource("XHSchool_ClassStudent");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHSchool_ClassStudent';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhschoolClassstudent[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhschoolClassstudent
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * @param $studId
     * @param $classId
     * @param int $op
     * @return XhschoolClassstudent
     * 创建班级学生记录
     * create by ck 20160815
     */
    public static function createRecord($studId, $classId, $op=0){
        $obj = new self;
        $obj->iStudId       = $studId;
        $obj->iSCLId        = $classId;
        $obj->iOp           = $op;
        return $obj;
    }

    /**
     * 根据开班ID获取班级ID，再删除学生
     *
     * @param $openClassId
     * @return mixed
     *
     * create by ck 20160929
     */
    public static function deleteRecordByOpenClassId($openClassId)
    {
        $classId = XhschoolClasslist::getClassIdByOpenClassId($openClassId);
        if(!$classId) return true;
        return self::find([
            'conditions'    => 'iSCLId IN ({idArr:array})',
            'bind'          => ['idArr' => $classId]
        ])->delete();
    }

    /**
     * @param $classId
     * @return XhschoolClassstudent[]
     * 根据班级ID返回学生信息
     * create by ck 20160816
     */
    public static function findByClassId($classId){
        return self::find(array(
            'conditions'    => 'bDelete = 0 AND iSCLId = :iClassId:',
            'bind'          => array(
                'iClassId'      => $classId
            )
        ));
    }

    /**
     * 根据师生关系接口返回的学生数组批量插入数据
     *
     * @param $studIdArr        --学生ID数组
     * @param $classId          --班级ID（数据库临时ID）
     * @param int $op           --操作码
     * @return bool
     *
     * create by ck 20160929
     */
    public static function batchCreateStudent($studIdArr, $classId, $op = 0){
        if(count($studIdArr) < 1) return true;
        $userId = Main::getLoginUserInfo('userId');
        $studentSql = 'INSERT INTO XHSchool_ClassStudent (iSCLId,iStudId,iOp,bDelete,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId) VALUES ';
        $valueArr = array();
        $nowTime = date('Y-m-d H:i:s');
        foreach($studIdArr as $studId){
            $valueArr[] = "({$classId},{$studId},{$op},0,'{$nowTime}',{$userId},'{$nowTime}',{$userId})";
        }
        $studentSql .= implode(',', $valueArr);
        return Di::getDefault()->get('db')->execute($studentSql);
    }

    /**
     * 根据班级ID及学校ID创建原生sql语句，查询不在班级中该学校的学生
     *
     * @param $classId
     * @param int $schoolId
     * @return mixed
     *
     * create by ck 20160929
     * modify by ck 20170508    优化sql结构，提高速度
     */
    public static function createSqlForOutStudByClassId($classId, $schoolId = 0)
    {
        $queryArr['columns'] = ['iUserId', 'sLogonName', 'sUserName', 'sSelfPhone', 'iUserSex', 'sAdClsName'];
//        $queryArr['query']   = "SELECT :columns: FROM XHSys_User AS U LEFT JOIN (SELECT * FROM XHSchool_ClassStudent WHERE bDelete = 0 AND iOp <> 2 AND iSCLId = {$classId}) AS S ON U.iUserId = S.iStudId WHERE U.iUserType = 1 AND U.bDelete = 0 AND IFNULL(S.iSCLId,0) <> {$classId} AND IFNULL(S.bDelete,0) = 0";
        $queryArr['query']   = "SELECT :columns: FROM XHSys_User WHERE iUserId NOT IN (SELECT iStudId FROM XHSchool_ClassStudent WHERE bDelete = 0 AND iOp <> 2 AND iSCLId = {$classId}) AND iUserType = 1 AND bDelete = 0 AND bCompany = 0 AND bDisable = 0 AND bHistory = 0";
        $schoolId and $queryArr['query'] .= " AND iSchoolId = {$schoolId}";
        return $queryArr;
    }

    /**
     * 根据学生ID数组及班级ID判断是否原本存在，如存在则将op改回0，学生ID数组改为差集，并返回操作结构
     *
     * @param $studIdArr
     * @param $classId
     * @return bool             --是否成功
     *
     * create by ck 20160930
     */
    public static function addOriginalStudIntoClass(&$studIdArr, $classId)
    {
        $studInClassId = XhschoolClassstudent::find(array(
            'columns'       => 'iStudId',
            'conditions'    => 'iSCLId=:iClassId: AND bDelete = 0 AND iOp = 2 AND iStudId IN ({idArr:array})',
            'bind'          => array(
                'iClassId'      => $classId,
                'idArr'         => $studIdArr
            )
        ))->toArray();
        if(empty($studInClassId)) return true;
        $studInClassId = array_column($studInClassId, 'iStudId');
        $studIdArr = array_diff($studIdArr, $studInClassId);
        $phql = 'UPDATE \\Admin\\Models\\school\\XhschoolClassstudent SET iOp = 0, tLastModifyDate = :nowTime:, iLastModifyUserId = :userId: WHERE iStudId IN ({idArr:array}) AND iSCLId = :classId:';
        return Di::getDefault()->get('modelsManager')->executeQuery($phql, [
            'idArr'     => $studInClassId,
            'classId'   => $classId,
            'nowTime'   => date('Y-m-d H:i:s'),
            'userId'    => Main::getLoginUserInfo('userId')
        ]);

    }

    /**
     * 根据学生ID及班级ID删除学生信息（如op为1则设置bDelete=1，如op为0则设置op=2）
     *
     * @param $studIdArr
     * @param $classId
     * @return bool             --是否成功
     *
     * create by ck 20160930
     */
    public static function delStudOutClass($studIdArr, $classId)
    {
        $query = XhschoolClassstudent::find(array(
            'conditions'    => 'bDelete = 0 AND iSCLId = :classId: AND iStudId IN ({idArr:array}) AND iOp = 1',
            'bind'          => ['classId' => $classId, 'idArr' => $studIdArr]
        ))->delete();
        if(!$query) return false;
        $phql = 'UPDATE \\Admin\\Models\\school\\XhschoolClassstudent SET iOp = 2, tLastModifyDate = :nowTime:, iLastModifyUserId = :userId:  WHERE bDelete = 0 AND iSCLId = :classId: AND iOp = 0 AND iStudId IN ({idArr:array})';
        return Di::getDefault()->get('modelsManager')->executeQuery($phql, [
            'idArr'     => $studIdArr,
            'classId'   => $classId,
            'nowTime'   => date('Y-m-d H:i:s'),
            'userId'    => Main::getLoginUserInfo('userId')
        ]);
    }

}
